﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BibMan.model.database;
using BibMan.model.database.Referencer;
using BibMan.controller;

namespace BibMan.model {

    /// <summary>
    /// Delegate type for model events
    /// </summary>
    public delegate void systemHandler();

    public sealed class Model {

        /// <summary>
        /// Event thrown when the database is loaded
        /// </summary>
        public event systemHandler DatabaseLoaded;
        private void FireDatabaseLoaded() {
            if (DatabaseLoaded != null) DatabaseLoaded();
        }

        /// <summary>
        /// Event thrown when a new database is created
        /// </summary>
        public event systemHandler DatabaseCreated;
        private void FireDatabaseCreated() {
            if (DatabaseCreated != null) DatabaseCreated();
        }

        private static volatile Model instance;
        private static object syncRoot = new Object();
        public static Model Instance {
            get {
                if (instance == null) {
                    lock (syncRoot) {
                        if (instance == null)
                            instance = new Model();
                    }
                }

                return instance;
            }
        }

        public Database Database { get; private set; }
        public String Filename { get; set; }
        
        private Model() {
            this.Filename = Program.filename;
        }

        public void LoadDatabase(String filename) {
            this.Filename = filename;
            Console.WriteLine("Loading from {0}", Filename);
            this.Database = DatabaseLoader.Load(filename);
            FireDatabaseLoaded();
        }

        public void SaveDatabase(String filename) {
            this.Filename = filename;
            DatabaseLoader.Save(Database, filename);
        }

        public void NewDatabase() {
            this.Filename = null;
            this.Database = new Database();
            FireDatabaseCreated();
        }
    }
}
